<template>
  <!-- 个人数据查询页面 -->
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" :model="queryForm">
      <el-form-item label="用户真实姓名" prop="userRealName">
        <el-select v-model="queryForm.id" filterable placeholder="请选择">
          <el-option v-for="item in options" :key="item.id" :label="item.mobile + '-' + item.userRealName"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="formModel.startTime" type="date" @change="selectStartDate" value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="formModel.endTime" type="date" @change="selectEndDate" value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-download" :loading="loadingDown" size="mini"
          @click="handleDownLoad">下载会员数据</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>

    <el-table v-loading="loading" border :data="orderList" style="width: 100%" @sort-change="handleSortChange">
      <el-table-column align="center" label="日期" prop="date" width="200" />
      <el-table-column align="center" label="买单金额" prop="totalOrderPrice" width="150" />
      <el-table-column align="center" label="卖单金额" prop="saleOrderPrice" width="150" />
      <!-- <el-table-column align="center" label="回款差额" prop="goodsprice" width="150" /> -->
      <el-table-column align="center" label="服务费" prop="totalListingFee" width="150" />
      <el-table-column align="center" label="采购补贴" prop="totalIncomeListingCash" width="150" />
      <el-table-column align="center" label="积分补贴" prop="totalIncomeListingPoints" width="150" />
      <el-table-column align="center" label="推荐奖励" prop="totalRecommendRewardCash" width="150" />
      <el-table-column align="center" label="提现金额" prop="totalWithdrawalAmount" width="150" />
    </el-table>

    <pagination v-show="total" :total="total" :page.sync="queryForm.pageNum" :limit.sync="queryForm.pageSize"
      @pagination="getList" />
  </div>
</template>
<script>
import {
  shopOrderLogsList, excelShopOrderLogsList, listChannel, listUser, updateSaleStatus, exporCgOrderListtData, ListGoodsOptions, downCgOrder, upCgOrder, getAdjustmentSwitch
} from '@/api/shop/order'
import { getPersonalBenefitsList, exporPersonalBenefitsList } from '@/api/shop/user/member'
import { yuan } from '@/utils'
import { excelNameDate } from '@/utils/index'


export default {
  name: 'AdjOrderList',
  filters: {
    yuan
  },
  data() {
    return {
      loading: false,
      // 列表总数
      total: 0,
      // 日期范围
      dateRange: [],
      totalBuy: 10000,
      totalSale: 11000,
      totalIncome: 0,
      // 订单状态数据字典
      orderStatusOptions: [],
      // 查询参数
      queryForm: {
        id: undefined,
        startTime: undefined,
        endTime: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      // 角色列表
      orderList: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      channels: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      formModel: {
        tableData: []
      },
      options: [],
      loadingDown: false
    }
  },
  created() {
    this.getOptions()
    // this.getList()
    this.getChannel()
  },
  methods: {
    selectStartDate(val) {
        let end = this.queryForm.endTime
        const sYear = new Date(val).getFullYear()
        const sDay = new Date(val).getDate()
        const sMon = new Date(val).getMonth() + 1
        const seDate = new Date(sYear, sMon, 0).getDate();
        const sEnd = new Date(end).getDate()
        const eMon = new Date(end).getMonth() + 1
        this.$set(this.queryForm, 'startTime', val)

        if (sMon != eMon) {
          // alert(seDate)
          if (seDate - sDay + sEnd > 29) {
            this.$message.error('只可选择三十日内')
            return false
          }
        } else {
          // alert(`${sEnd}-${sDay}=${sEnd-sDay}`)
          if (sEnd - sDay > 29) {
            this.$message.error('只可选择三十日内')
            return false
          }
        }
    },
    selectEndDate(val) {
        let start = this.queryForm.startTime
        const sYear = new Date(start).getFullYear()
        const sDay = new Date(start).getDate()
        const sMon = new Date(start).getMonth() + 1
        const seDate = new Date(sYear, sMon, 0).getDate();
        const sEnd = new Date(val).getDate()
        const eMon = new Date(val).getMonth() + 1
        this.$set(this.queryForm, 'endTime', val)

        if (sMon != eMon) {
          // alert(seDate)
          if (seDate - sDay + sEnd > 29) {
            return this.$message.error('只可选择三十日内')
          }
        } else {
          // alert(`${sEnd}-${sDay}=${sEnd-sDay}`)
          if (sEnd - sDay > 29) {
            return this.$message.error('只可选择三十日内')
          }
        }

    },
    // 获取买家
    async getOptions() {
      const {
        map: { userList }
      } = await listUser()
      this.options = userList
    },
    async onConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          return
        }
        await splitOrderReq({ ...this.formModel })
        this.$message.success('操作成功')
        this.formModel = {}
        this.$refs.formRef.resetFields()
        this.getList()
        this.showOrderVisible = false
      })
    },
    handleOrder(record) {
      this.formModel.orderId = record.id
      this.showOrderVisible = true
    },
    handleStatus(record) {
      updateSaleStatus({ 'orderId': record.id }).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
        this.getList()
      })
    },
    getChannel() {
      listChannel().then((response) => {
        this.channels = response.map.data
      })
    },
    handleQuery() {
      if (this.queryForm.id == undefined) {
        return this.$message.error('用户必须选')
      }
      console.log(this.queryForm)
      if (this.queryForm.startTime == undefined || this.queryForm.endTime == undefined) {
        return this.$message.error('开始结束时间必须选')
      }
      let val = this.queryForm.startTime
      let end = this.queryForm.endTime
      const sYear = new Date(val).getFullYear()
      const sDay = new Date(val).getDate()
      const sMon = new Date(val).getMonth() + 1
      const seDate = new Date(sYear, sMon, 0).getDate();
      const sEnd = new Date(end).getDate()
      const eMon = new Date(end).getMonth() + 1
      if (sMon != eMon) {
        // alert(seDate)
        if (seDate - sDay + sEnd > 29) {
          this.$message.error('只可选择三十日内')
          return false
        }
      } else {
        if (sEnd - sDay > 29) {
          this.$message.error('只可选择三十日内')
          return false
        }
      }
      this.orderList = []
      this.getList()
    },
    /**
           * 表单重置
           */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.handleQuery()
    },
    async getList() {
      
      const {
        map: {
          page: { records: data, total },
        }
      } = await getPersonalBenefitsList({...this.queryForm})
      this.total = total
      data.forEach(item => {
        if (item.buymoney == null) {
          item.buymoney = 0
        }
        if (item.selloutMoney == null) {
          item.selloutMoney = 0
        }
        if (item.income == null || item.income < 0) {
          item.income = 0
        }
      })
      this.orderList = data
      console.log(this.orderList)
      this.loading = false
    },
    /**
           * 后端排序
           */
    handleSortChange(sort) {
      this.queryForm.sortName = sort.prop
      this.queryForm.sortOrder = sort.order
      console.log(sort)
      this.getList()
    },
    async handleDetail(row) {
      const {
        map: { data }
      } = await getOrder(row.id)
      this.orderDetail = data
      this.orderDialogVisible = true
    },
    handleShip(row) {
      this.shipForm = {
        orderId: row.id,
        shipChannel: undefined,
        shipSn: undefined
      }
      this.shipDialogVisible = true
    },
    clickShip(row) {
      this.$refs['shipForm'].validate(async (valid) => {
        if (valid) {
          const { code, msg } = await clickShip(this.shipForm)
          if (code === 200) {
            this.$message.success('发货成功')
            this.shipDialogVisible = false
            this.getList()
          } else {
            this.$message.error(msg)
          }
        }
      })
    },
    handleRefund(row) {
      this.$confirm(
        '是否确认为订单编号为 [' + row.orderSn + '] 的订单退款?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return refundOrder(row.id)
        })
        .then(() => {
          this.getList()
          this.$message.success('退款成功')
        })
        .catch(function (e) { })
    },
    // 下架商品
    handleCancelOrder(row) {
      this.$confirm(
        '是否确认为商品编号为 [' + row.id + '] 的商品下架?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return refundOrder(row.id)
        })
    },
    /**
           * 删除按钮
           */
    async handleDelete(row) {
      const orderId = row.id
      this.$confirm(
        '是否确认删除订单编号为 [' + row.orderSn + '] 的订单吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return delOrder(orderId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
        .catch(function (e) { })
    },
    handleDownLoad() {
      if (this.queryForm.id == undefined) {
        return this.$message.error('用户必须选')
      }
      if (this.queryForm.startTime == undefined || this.queryForm.endTime == undefined) {
        return this.$message.error('开始结束时间必须选')
      }
      let val = this.queryForm.startTime
      let end = this.queryForm.endTime
      const sYear = new Date(val).getFullYear()
      const sDay = new Date(val).getDate()
      const sMon = new Date(val).getMonth() + 1
      const seDate = new Date(sYear, sMon, 0).getDate();
      const sEnd = new Date(end).getDate()
      const eMon = new Date(end).getMonth() + 1
      if (sMon != eMon) {
        // alert(seDate)
        if (seDate - sDay + sEnd > 29) {
          this.$set(this.queryForm, 'startTime', undefined)
          this.$message.error('只可选择三十日内')
          return false
        }
      } else {
        if (sEnd - sDay > 29) {
          this.$message.error('只可选择三十日内')
          return false
        }
      }
      let id = this.queryForm.id
      let userRealName
      this.options.forEach(item=>{
        if(item.id == id){
          userRealName = item.userRealName
        }
      })
      this.$confirm(
        `是否下载${this.queryForm.id}会员收益记录表`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
        .then(res => {
          // let data = {
          //   id:this.queryForm.id,
          //   startTime:this
          // }
          exporPersonalBenefitsList({...this.queryForm,userRealName}).then(res => {
            const blob = new Blob([res.data], { type: 'application/msword' })// new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
            console.log(blob)
            const fileName = `编号${this.queryForm.id}会员${this.queryForm.startTime}至${this.queryForm.endTime}收益列表.xls`// 下载文件名称
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
          })
          // this.loadingDown = true
          console.log(res)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.more_btn {
  margin-left: 10px;
}
</style>
